package com.lilanz.microservice.express.utils.log;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @ Description：全局日志统一获取
 */
@Aspect
@Component//将这个类引入spring容器中去
public class WebLogAspect {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //要处理的方法，包名+类名+方法名  要注意子包在子包等要多加个*
    @Pointcut("execution(public * com.lilanz.microservice.express.controller.Controller.*(..))")
    public void cut() {
    }

    @Before("cut()")//在调用上面 @Pointcut标注的方法前执行以下方法
    public void doBefore(JoinPoint joinPoint) throws Throwable {//用于获取类方法
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        logger.info("《===============================开始记录=====================================》");
        //url
        logger.info("请求的接口 ：" + request.getRequestURI());
        //method
        logger.info("请求的方法 ：" + request.getMethod());
        //ip
        logger.info("用户IP ： " + request.getRemoteAddr());
        //类方法
        logger.info("被访问类的全路径 ：" + joinPoint.getSignature().getDeclaringTypeName() + '.' + joinPoint.getSignature().getName());//获取类名及类方法
        //参数
        Enumeration<String> enu = request.getParameterNames();
        while (enu.hasMoreElements()) {
            String name = enu.nextElement();
            logger.info("传入的参数名:" + name + " " + "传入的参数值:" + request.getParameter(name));
        }

    }

    @After("cut()")//无论Controller中调用方法以何种方式结束，都会执行
    public void doAfter() throws Throwable {
    }

    @AfterReturning(returning = "obj", pointcut = "cut()")//在调用上面 @Pointcut标注的方法后执行。用于获取返回值
    public void doAfterReturning(Object obj) throws Throwable {
        if (obj != null) {
            logger.info("返回给用户的结果 : " + obj.toString());
        }
        logger.info("《===============================结束记录=====================================》");

    }

}
